// 获取图片链接
function getImage(image) {
    return `/common/download?name=${image}`;
}

let hotelDetail = localStorage.getItem('hotelDetail');
hotelDetail = JSON.parse(hotelDetail);


window.addEventListener("DOMContentLoaded", function () {
    const hotelDetailBox = document.querySelector('.hote-detail')

    const image = getImage(hotelDetail.image);
    let html = ""
    html += `
<div class="introduce">
        <img src="${image}" alt="">
            <div class="content">
                <div class="name">
                    ${hotelDetail.hotelName}
                </div>
                <ul class="label">
                    <li>位置优越</li>
                    <li>服务态度好</li>
                    <li>房间干净</li>
                </ul>
                <div class="address">地址:${hotelDetail.hotelAddress}</div>
                <div class="build-time">装修时间:2021年</div>
                <div class="connection">联系电话:${hotelDetail.telephone}</div>
                <div class="score">${hotelDetail.score}分</div>
                <div class="assessment">98%好评 6632条评论 199条问答></div>
            </div>
    </div>
        <div class="reservation">
            <div class="tit">房型预定</div>
        <div class="live-time">
            <span>入住</span>
            <input type="date" class="stay">
                <span>离店</span>
                <input type="date" class="leave">
        </div>
        <div class="choice">
            <span>房型</span>
            <span>床型</span>
            <span>入住人数</span>
            <span>房价</span>
        </div>`

    let count = 1
    hotelDetail.hotelRoomCategories.forEach(function (hotelRoom) {

        const roomImage = getImage(hotelRoom.roomImage)
        html += `
                <div class="big-bed${count}">
                <img src="${roomImage}" alt="">
                <div class="room-type">
                <div class="room-name">${hotelRoom.roomName}</div>
<!--                    <div class="area">13-15m² 1.5m双人床</div>-->
            </div>
            <div class="p-count">2人</div>
            <div class="price">${hotelRoom.roomPrice}</div>
            <button class="hotel-reservation">预定</button>
        </div>
        `
        count += 1
    })


    html +=
        `</div>

        <div class="information">
            <div class="tit">酒店详情</div>
            <div class="tab">
                <table style="width: 1000px; height: 30px;">
                    <tr>
                        <td style="width: 100px; height: 40px;">酒店亮点</td>
                        <td>战略合作酒店，城市销量前列，优质服务保障，提供去哪儿平台专属低价</td>
                    </tr>
                    <tr>
                        <td>联系方式</td>
                        <td>+86 ${hotelDetail.telephone}</td>
                    </tr>
                    <tr>
                        <td>基本信息</td>
                        <td>230间客房</td>
                    </tr>
                    <tr>
                        <td>酒店简介</td>
                        <td>
                            <p>${hotelDetail.description}</p>
                        </td>
                    </tr>
                </table>
            </div>

        </div>`

    hotelDetailBox.innerHTML = html

    // 酒店时间预定
    const stayTime = document.querySelector('.box .reservation .live-time .stay')
    const leaveTime = document.querySelector('.box .reservation .live-time .leave')

    stayTime.addEventListener('click', function () {
        // 获取当前日期并格式化为 yyyy-MM-dd
        let today = new Date().toISOString().slice(0, 10);
        console.log(today);

        // 将当前日期设置为最小值
        stayTime.min = today;
    })

    leaveTime.addEventListener('click', function () {
        console.log('点击了第二个');
        const stayTime = document.querySelector('.box .reservation .live-time .stay')
        const newdate = new Date(stayTime.valueAsDate);
        newdate.setDate(newdate.getDate() + 1);
        leaveTime.min = new Date(newdate).toISOString().slice(0, 10);
        // console.log(stayTime);
    })
    // localStorage.removeItem('hotelDetail');

    //预约按钮点击事件
    const hotelReservation = document.querySelectorAll('.hotel-reservation')

    for (let i = 0;i<hotelReservation.length;i++){
        hotelReservation[i].addEventListener('click',function (){
            const stayTime = $(".box .reservation .live-time .stay").val();
            const leaveTime = $(".box .reservation .live-time .leave").val();
            if(stayTime && leaveTime){
                function dateDiffInDays(date1Str, date2Str) {
                    // 将日期字符串转换成Date对象
                    let date1 = new Date(date1Str);
                    let date2 = new Date(date2Str);

                    // 计算时间差（以毫秒为单位）
                    let timeDiff = Math.abs(date2.getTime() - date1.getTime());

                    // 将时间差转换成天数
                    let diffInDays = Math.ceil(timeDiff / (1000 * 3600 * 24));

                    return diffInDays;
                }
                // 获取URL参数
                const urlParams = new URLSearchParams(window.location.search);
                const hid = urlParams.get('hid');

                //预约的套房名称
                // const reservationRoom = $(`.room-name:nth-child(${i+1})`).textContent;
                const reservationRoom = document.querySelector(`.big-bed${i+1} .room-name`).innerHTML
                const roomPrice = document.querySelector(`.big-bed${i+1} .price`).innerHTML

                //预约的价格  天数*单天价格
                let days = dateDiffInDays(stayTime,leaveTime);

                const totalPrice = days*roomPrice

                // 构建请求数据对象
                let requestData = {
                    hid: hid,
                    stayTime: stayTime,
                    leaveTime: leaveTime,
                    totalPrice: totalPrice,
                    reservationRoom: reservationRoom
                };

                // 发送 Ajax 请求
                $.ajax({
                    url: "/hotel/reservation",
                    type: "POST",
                    contentType: "application/json",
                    data: JSON.stringify(requestData),
                    success: function (response) {
                        // 处理响应
                        if (response.success === 1) {
                            alert("预约成功");
                            // 进行跳转或其他操作
                            // localStorage.setItem('responseData', JSON.stringify(response.data.username));
                            // window.location.href = 'index.html'
                        } else {
                            alert("预约失败");
                        }
                    },
                    error: function () {
                        alert("请求失败");
                    }
                })
            }else {
                alert("请输入预约时间获离开时间")
            }

        })
    }
})



